package com.qq.googleplay.ui.fragment;

import android.graphics.Color;
import android.os.SystemClock;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.haarman.listviewanimations.swinginadapters.AnimationAdapter;
import com.haarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.qq.googleplay.http.Protocol.HomeProtocol;
import com.qq.googleplay.base.BaseFragment;
import com.qq.googleplay.base.BaseHolder;
import com.qq.googleplay.base.LoadingPager;
import com.qq.googleplay.base.SuperBaseAdapter;
import com.qq.googleplay.bean.AppInfoBean;
import com.qq.googleplay.bean.HomeBean;
import com.qq.googleplay.factory.ListViewFactory;
import com.qq.googleplay.factory.ThreadPoolFactory;
import com.qq.googleplay.ui.holder.HomeHolder;
import com.qq.googleplay.ui.holder.PictureHolder;
import com.qq.googleplay.utils.UIUtils;
import com.qq.googleplay.ui.widget.CustomSwipeToRefresh;

import java.util.List;

/**
 * ============================================================
 * 版 权 ： Google互联网有限公司版权所有 (c) 2016
 * 作 者 : 陈冠杰
 * 版 本 ： 1.0
 * 创建日期 ：2016/3/20 17:37
 * 描 述 ：  主页
 * 修订历史 ：
 * ============================================================
 **/
public class HomeFragment extends BaseFragment {


    private HomeProtocol mHomeProtocol;
    private List<AppInfoBean> mData;//listview的数据源
    private List<String> mPicture;//轮播图的数据
    private List<String> mDesc;//轮播图的title

    private HomeAdapter mHomeAdapter;
    private CustomSwipeToRefresh mRefreshLayout;
    private ListView mListView;
    private AnimationAdapter mAnimAdapter;
    public PictureHolder mPictureHolder;
    private View mHeaderView;
    private ViewTreeObserver mViewTreeObserver;
    // private CircleRefreshLayout mRefreshLayout;

    /*private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mRefreshLayout.finishRefreshing();
        }
    };*/

  /*  @Override
    public void onResume() {
        super.onResume();
        if (mViewTreeObserver != null) {
            mViewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver
                    .OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {
                    mPictureHolder.onPageSelected(0);
                }
            });
        }
    }
*/
    @Override//加载数据
    protected LoadingPager.LoadedResult initData() {

        mHomeProtocol = new HomeProtocol();

        try {
            HomeBean homeBean = mHomeProtocol.loadData(0);
            LoadingPager.LoadedResult state = checkState(homeBean);

            // 如果不成功,就直接返回,走到这里说明homeBean是ok
            if (state != LoadingPager.LoadedResult.SUCCESS) {
                return state;
            }
            // 如果不成功,就直接返回,走到这里说明homeBean.list是ok
            state = checkState(homeBean.list);
            if (state != LoadingPager.LoadedResult.SUCCESS) {
                return state;
            }
            mData = homeBean.list;
            mPicture = homeBean.picture;
            mDesc = homeBean.des;
            return LoadingPager.LoadedResult.SUCCESS;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return LoadingPager.LoadedResult.ERROR;
        }
    }

    @Override
    protected View initSuccessView() {

        // View view = View.inflate(UIUtils.getContext(), R.layout_cb.layout_refresh, null);

        // mRefreshLayout = (CircleRefreshLayout) view.findViewById(R.id.refresh_layout);
        // ListView listView = (ListView) view.findViewById(R.id.list);
        mRefreshLayout = new CustomSwipeToRefresh(UIUtils.getContext());
        mRefreshLayout.setColorSchemeColors(Color.BLUE, Color.RED);

        //返回成功的视图
        mListView = ListViewFactory.createListView();
        mListView.setBackgroundColor(Color.parseColor("#eaeaea"));

        mPictureHolder = new PictureHolder(mActivity);
        mPictureHolder.setDataAndRefreshHolderView(mPicture);

        mHeaderView = mPictureHolder.getHolderView();
      //  ViewPager viewPager = (ViewPager) mHeaderView.findViewById(R.id.item_home_picture_pager);
        //mViewTreeObserver = viewPager.getViewTreeObserver();
        mHomeAdapter = new HomeAdapter(mListView, mData);
        mListView.addHeaderView(mHeaderView);

        //给listview的item添加“底部追加”动画
        mAnimAdapter = new SwingBottomInAnimationAdapter(mHomeAdapter);
        mAnimAdapter.setAbsListView(mListView);
        mListView.setAdapter(mAnimAdapter);

        // listView.setAdapter(mHomeAdapter);
        mRefreshLayout.addView(mListView);
        initListener();
        /* app:AniBackColor="#ff8b90af"
        app:AniForeColor="#ffffffff"
        app:CircleSmaller="6"
        android:id="@+id/refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">*/


        // refreshLayout.addView(listView);
       /* mRefreshLayout.setOnRefreshListener(new CircleRefreshLayout.OnCircleRefreshListener() {
            @Override
            public void completeRefresh() {

            }

            @Override
            public void refreshing() {
                ThreadPoolFactory.getNormalPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        SystemClock.sleep(2000);
                    }
                });
            }
        });*/
       /* mPictureHolder.getViewPager().getViewTreeObserver().addOnGlobalLayoutListener(new
      ViewTreeObserver.OnGlobalLayoutListener() {


            @Override
            public void onGlobalLayout() {
                mPictureHolder.onPageSelected(0);
            }
        });*/
        return mRefreshLayout;
    }

    private void initListener() {
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                ThreadPoolFactory.getNormalPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        SystemClock.sleep(2000);
                        UIUtils.postTaskSafely(new Runnable() {
                            @Override
                            public void run() {
                                mAnimAdapter.notifyDataSetChanged();
                                mRefreshLayout.setRefreshing(false);
                            }
                        });
                    }
                });
            }
        });
    }


    class HomeAdapter extends SuperBaseAdapter<AppInfoBean> {

        public HomeAdapter(AbsListView listView, List<AppInfoBean> dataSource) {
            super(listView, dataSource);
        }

        @Override
        public BaseHolder<AppInfoBean> getSpecialHolder(int position) {
            return new HomeHolder(mActivity);
        }

        @Override
        public List<AppInfoBean> onLoadMore() throws Throwable {
            return loadMore(mData.size());
        }

        @Override
        public void onNormalItemClick(AdapterView<?> parent, View view, int position, long id) {
            super.onNormalItemClick(parent, view, position, id);
        }
    }

    private List<AppInfoBean> loadMore(int index) throws Throwable {

        HomeBean homeBean = mHomeProtocol.loadData(index);
        if (homeBean == null) {
            return null;
        }

        if (homeBean.list == null || homeBean.list.size() == 0) {
            return null;
        }

        return homeBean.list;
    }

   /* @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser){
            getLoadingPager().loadData();
        }
    }*/


}
